<template>
  <div>
    <el-dialog v-bind="$attrs" v-on="$listeners" @open="onOpen" @close="onClose" title="配置网站WordPres的Id" width="35%">
      <div class="sub-title">网站名称：{{wpKeyEntity.siteName}}</div>
      <div class="sub-title">网站域名：{{wpKeyEntity.siteUrl}}</div>
      <el-form ref="form" :model="form" size="small" label-width="180px"
               label-position="left">
        <div v-for="(item, index) in form.items" :key="index" class="group-container">

          <el-form-item :label="'WordPresId映射-' + (index + 1)" :prop="'items[' + index + '].wpCategory'" :rules="{ required: true, message: 'WordPressId不能为空' }">
            <el-input type="number"
              v-model="item.wpCategory"
              placeholder="请输入WordPressId"
            ></el-input>
          </el-form-item>
          <el-form-item :label="'关键词表Id-' + (index + 1)" :prop="'items[' + index + '].dictCategoryId'" :rules="{ required: true, message: '关键词Id不能为空' }">
            <el-select :label="'关键词表Id-' + (index + 1)" :prop="'items[' + index + '].dictCategoryId'" :rules="{ required: true, message: '关键词Id不能为空' }"
                       v-model="item.dictCategoryId" placeholder="请选择关键词" filterable clearable
                       :style="{width: '100%'}">
              <el-option v-for="(pareItem, pareIndex) in parentList" :key="pareIndex" :label="pareItem.parentCategoryName+'('+pareItem.parentCategoryId+')'"
                         :value="pareItem.parentCategoryId" :disabled="pareItem.disabled"></el-option>
            </el-select>
          </el-form-item>
          <div class="group-header">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click.prevent="removeItem(index)"
            >删除</el-button>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.prevent="addItem" type="primary">添加组</el-button>
        <el-button type="success" @click="submitForm">提交</el-button>
        <el-button @click="close">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { listCategoryParentId } from "@/api/dict/category";
import {
  addCategory,listCategory
} from "@/api/wp/keyCategory";

export default {
  name:'AddCategory',
  inheritAttrs: false,
  components: {},
  props:{
    wpKeyEntity: {
      type: Object,
      default: () => ({
        id:null,
        siteName:null,
        siteUrl:null
      })
    },
  },
  data() {
    return {
      parentList:[
        {
        "parentCategoryName": "默认数据1",
        "parentCategoryId": 1
        }, {
          "parentCategoryName": "默认数据2",
          "parentCategoryId": 2
        }
      ],
      form: {
        items: [{ wpCategory: 111, dictCategoryId: 222 }]
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getList();
  },
  mounted() {
  },
  methods: {
    getList(){
      listCategoryParentId().then(response => {
        console.log(response.rows)
        this.parentList = response.rows
        console.log(this.parentList)
      });
    },
    removeItem(index) {
      this.form.items.splice(index, 1);
    },
    addItem() {
      this.form.items.push({ wpCategory: '', dictCategoryId: '' });
    },
    submitForm() {
      // 在这里处理提交的数据，例如发送请求到后端
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 在发送请求之前，确保 wpCategory 值始终为数字类型
          const requestData = this.form.items.map(item => ({
            ...item,
            wpCategory: Number(item.wpCategory), // 将 wpCategory 转换为数字类型
            wpKeyId: this.wpKeyEntity.id
          }));
          let date = {
            "wpKeyCategoryList":requestData,
            "wpKeyId":this.wpKeyEntity.id
          }
          // 在这里处理提交的数据，例如发送请求到后端
          addCategory(date).then(response=>{
            this.$message.success("提交成功！");
            this.$emit('update:visible', false)
          }).catch((error) => {
              console.error("发生错误：", error);
              // 进一步处理错误
            });
        } else {
          console.log("表单验证失败");
          return false;
        }
      });
    },
    onOpen() {
      console.log(this.wpKeyEntity);
      let data = {
        wpKeyId : this.wpKeyEntity.id
      }
      listCategory(data).then(response=>{
        console.log("this.form.items= response.rows")
        this.form.items = response.rows.map(row => ({
          wpCategory: row.wpCategory || "", // 假设 response.rows 中的元素包含 wpCategory 属性
          dictCategoryId: row.dictCategoryId || "", // 假设 response.rows 中的元素包含 dictCategoryId 属性
          id: row.id || "" // 假设 response.rows 中的元素包含 dictCategoryId 属性
        }));
        console.log( this.form.items)
      })
    },
    onClose() {

    },
    close() {
      this.$emit('update:visible', false)
    },
  }
}

</script>
<style>
.sub-title {
  line-height: 30px;
  font-size: 16px;
  margin-top: 5px;
  margin-bottom: 10px;
  margin-left: 2%;
}
.group-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.group-header {
  position: relative;
  text-align: right;
}
</style>
